package com.example.cherrymonitor.service;

import com.example.cherrymonitor.dao.WarnDataDao;
import com.example.cherrymonitor.entity.WarnData;
import com.example.cherrymonitor.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WarnDataService{
    @Autowired
    private WarnDataDao warnDataDao;

    @Autowired
    private IdWorker idWorker;



    /**
     * 查询全部列表
     * @return
     */
    public List<WarnData> findAll() {
        Sort sort = new Sort(Sort.Direction.DESC,"colletionTime");
        return warnDataDao.findAll(sort);
    }


    /**
     * 条件查询+分页
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<WarnData> findSearch(Map whereMap, int page, int size) {
        Specification<WarnData> specification = createSpecification(whereMap);
        Sort sort = new Sort(Sort.Direction.DESC,"colletionTime");
        PageRequest pageRequest =  PageRequest.of(page-1, size,sort);
        return warnDataDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     * @param whereMap
     * @return
     */
    public List<WarnData> findSearch(Map whereMap) {
        Specification<WarnData> specification = createSpecification(whereMap);
        //这里之前出了一个bug就是sort里的colletionTime如果带有下划线会找不到，所以我把下划线去掉了
        Sort sort = new Sort(Sort.Direction.DESC,"colletionTime");
        return warnDataDao.findAll(specification,sort);
    }

    /**
     * 根据ID查询实体
     * @param id
     * @return
     */
    public WarnData findById(String id) {
        return warnDataDao.findById(id).get();
    }

    /**
     * 增加
     * @param warnData
     */
    public void add(WarnData warnData) {
        warnData.setId( idWorker.nextId()+"" );
        warnDataDao.save(warnData);
    }

    /**
     * 修改
     * @param warnData
     */
    public void update(WarnData warnData) {
        warnDataDao.save(warnData);
    }

    /**
     * 删除
     * @param id
     */
    public void deleteById(String id) {
        warnDataDao.deleteById(id);
    }

    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private Specification<WarnData> createSpecification(Map searchMap) {

        return new Specification<WarnData>() {

            @Override
            public Predicate toPredicate(Root<WarnData> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // id
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                    predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
                }
                // 设备id
                if (searchMap.get("equipmentId")!=null && !"".equals(searchMap.get("equipmentId"))) {
                    predicateList.add(cb.like(root.get("equipmentId").as(String.class), "%"+(String)searchMap.get("equipmentId")+"%"));
                }
                // 种类
                if (searchMap.get("category")!=null && !"".equals(searchMap.get("category"))) {
                    predicateList.add(cb.like(root.get("category").as(String.class), "%"+(String)searchMap.get("category")+"%"));
                }
                // 准确率
                if (searchMap.get("confidence")!=null && !"".equals(searchMap.get("confidence"))) {
                    predicateList.add(cb.like(root.get("confidence").as(String.class), "%"+(String)searchMap.get("confidence")+"%"));
                }
                // 日期
                if (searchMap.get("startTime") != null && !"".equals(searchMap.get("startTime"))) {
                    try {
                        System.out.println(searchMap.get("startTime")+"====="+searchMap.get("endTime"));
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        predicateList.add(cb.greaterThanOrEqualTo(root.get("colletionTime").as(Date.class), dateFormat.parse((String) searchMap.get("startTime"))));

                        if (searchMap.get("endTime") != null && !"".equals(searchMap.get("endTime"))) {
                            predicateList.add(cb.lessThanOrEqualTo(root.get("colletionTime").as(Date.class), dateFormat.parse((String) searchMap.get("endTime"))));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                // 害虫名字
                if (searchMap.get("pestName")!=null && !"".equals(searchMap.get("pestName"))) {
                    predicateList.add(cb.like(root.get("pestName").as(String.class), "%"+(String)searchMap.get("pestName")+"%"));
                }
                // 害虫id
                if (searchMap.get("pest_id")!=null && !"".equals(searchMap.get("pest_id"))) {
                    predicateList.add(cb.like(root.get("pest_id").as(String.class), "%"+(String)searchMap.get("pest_id")+"%"));
                }
                // 危害等级
                if (searchMap.get("harm_level")!=null && !"".equals(searchMap.get("harm_level"))) {
                    predicateList.add(cb.like(root.get("harm_level").as(String.class), "%"+(String)searchMap.get("harm_level")+"%"));
                }
                // 害虫数量
                if (searchMap.get("number")!=null && !"".equals(searchMap.get("number"))) {
                    predicateList.add(cb.like(root.get("number").as(String.class), "%"+(String)searchMap.get("number")+"%"));
                }
                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}

